'use strict';
var vk; // 全局vk实例
// 涉及的表名
const dbName = require("../../../dao/config.js");

var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	/**
	 * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
	 */
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包

		// 参数合法校验开始-----------------------------------------------------------
		let formValidateRes = await this._formValidate();
		if (formValidateRes.code !== 0) return formValidateRes;
		// 参数合法校验结束-----------------------------------------------------------
	},
	/**
	 * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
	 */
	_after: async function(options) {
		let { err, res } = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},
	_formValidate: async function() {
		let res = { code: 0, msg: '' };
		let rules = {};
		const methodName = this.getMethodName();
		const data = this.getParams();
		// 验证规则开始 -----------------------------------------------------------
		if (methodName === "add") {
			rules = {
				user_id: [
					{ required: true, message: '请选择用户', trigger: 'blur' },
				],
				lv: [
					{ required: true, message: '请选择等级', trigger: 'blur' },
					// 自定义
					{
						validator: function(rule, value, callback) {
							if (typeof value !== "number") {
								return callback(false);
							} else if (value <= 0) {
								return callback(false);
							} else {
								callback();
							}
						},
						trigger: 'blur',
						message: '请选择等级'
					}
				],
				position: [
					{ required: true, message: '请选择省市区', trigger: 'blur' },
				],
				add_time: [
					{ required: true, message: '起始时间不能为空', trigger: 'blur' },
				],
				reward_rule: [
					{ required: true, message: '请正确填写奖励规则', trigger: 'blur' },
					// 自定义
					{
						validator: function(rule, value, callback) {
							if (value.is_calc && value.is_fixed_calc && !value.fixed_value) {
								return callback(new Error('请正确填写奖励规则'));
							} else if (value.is_calc && !value.is_fixed_calc && !value.proportion_value) {
								return callback(new Error('请正确填写奖励规则'));
							} else {
								callback();
							}
						},
						trigger: 'blur',
						message: '请正确填写奖励规则'
					}
				]
			};
		} else if (methodName === "update") {
			rules = {
				_id: [
					{ required: true, message: 'ID不能为空', trigger: 'blur' },
				],
				reward_rule: [
					{ required: true, message: '请正确填写奖励规则', trigger: 'blur' },
					// 自定义
					{
						validator: function(rule, value, callback) {
							if (value.is_calc && value.is_fixed_calc && !value.fixed_value) {
								return callback(new Error('请正确填写奖励规则'));
							} else if (value.is_calc && !value.is_fixed_calc && !value.proportion_value) {
								return callback(new Error('请正确填写奖励规则'));
							} else {
								callback();
							}
						},
						trigger: 'blur',
						message: '请正确填写奖励规则'
					}
				]
			}
		}
		// 验证规则结束 -----------------------------------------------------------

		// 开始进行验证
		if (vk.pubfn.isNotNull(rules)) {
			res = vk.pubfn.formValidate({
				data: data,
				rules: rules
			});
		}
		// 返回验证结果
		return res;
	},
	/**
	 * 获取列表
	 * @url admin/business/sys.fxRegionalAgent.getList 前端调用的url参数地址
	 */
	getList: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		res = await vk.daoCenter.fxRegionalAgentDao.getTableData({
			data,
			// 副表列表
			foreignDB: [{
				dbName: "uni-id-users",
				localKey: "user_id",
				foreignKey: "_id",
				as: "userInfo",
				limit: 1,
				fieldJson: { token: false, password: false },
			}]
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 添加
	 * @url admin/business/sys.fxRegionalAgent.add 前端调用的url参数地址
	 */
	add: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			user_id,
			position,
			add_time,
			exp_time,
			reward_rule,
			remark,

			check_repeat = true, // 是否需要检测重复
		} = data;

		if (exp_time && exp_time.toString().indexOf("000") > -1) exp_time += 86399999;
		let userInfo = await vk.daoCenter.userDao.findById(user_id);
		if (vk.pubfn.isNull(userInfo)) return { code: -1, msg: "用户不存在" };

		let lv;
		if (vk.pubfn.isNotNull(position.area)) {
			lv = 3;
		} else if (vk.pubfn.isNotNull(position.city)) {
			lv = 2;
		} else if (vk.pubfn.isNotNull(position.province)) {
			lv = 1;
		} else {
			return { code: -1, msg: "请选择省市区" };
		}
		if (check_repeat) {
			let num = await vk.daoCenter.fxRegionalAgentDao.count({
				position,
				lv
			});
			if (num > 0) {
				return { code: -1, msg: "该区域已有人代理。" };
			}
		}
		await vk.daoCenter.fxRegionalAgentDao.add({
			user_id,
			position,
			lv,
			add_time,
			exp_time,
			reward_rule,
			remark
		});
		await vk.daoCenter.userDao.checkUserFxRole(user_id);
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 修改
	 * @url admin/business/sys.fxRegionalAgent.update 前端调用的url参数地址
	 */
	update: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			_id,
			add_time,
			exp_time,
			reward_rule,
			remark,
		} = data;

		if (exp_time && exp_time.toString().indexOf("000") > -1) exp_time += 86399999;

		res.info = await vk.daoCenter.fxRegionalAgentDao.updateAndReturn({
			whereJson: {
				_id
			},
			dataJson: {
				add_time,
				exp_time,
				reward_rule,
				remark,
			}
		});
		if (res.info.user_id) await vk.daoCenter.userDao.checkUserFxRole(res.info.user_id);
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 删除
	 * @url admin/business/sys.fxRegionalAgent.delete 前端调用的url参数地址
	 */
	delete: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			_id
		} = data;
		if (vk.pubfn.isNull(_id)) return { code: -1, msg: "id不能为空" };
		let fxRegionalAgentInfo = await vk.daoCenter.fxRegionalAgentDao.findById(_id);
		await vk.daoCenter.fxRegionalAgentDao.deleteById(_id);
		await vk.daoCenter.userDao.checkUserFxRole(fxRegionalAgentInfo.user_id);
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url admin/business/sys.fxRegionalAgent.test 前端调用的url参数地址
	 */
	test: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
};

module.exports = cloudObject;
